package com.example.administrator.hellocomp;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.widget.Toast;

import java.io.File;

public class recorderService extends Service {
    private MediaPlayer mPlayer;
    private MediaRecorder recorder;
    private File  sdpath  = Environment.getExternalStorageDirectory();
    public recorderService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate(){
        super.onCreate();
        init();



    }
    private void init()
    {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(sdpath.toString()+"/Music/recorder/"+System.currentTimeMillis()+".amr");

    }
    @Override
    public void onStart(Intent intent,int startId)
    {
        super.onStart(intent,startId);
        if(intent!=null)
        {

            Bundle bundle = intent.getExtras();
            int op = bundle.getInt("op");
            Toast.makeText(getApplicationContext(),"已经收到值了"+op,Toast.LENGTH_SHORT).show();
            switch (op)
            {
                case 0:
                    try{
                        recorder.prepare();
                        recorder.start();
                        Toast.makeText(getApplicationContext(),"开始录音了哦",Toast.LENGTH_SHORT).show();
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    break;
                case 1:
                    if(recorder!=null)
                    {
                        try{
                            recorder.stop();
//                            recorder.reset();
                            recorder.release();

                            recorder = null;
                            Toast.makeText(getApplicationContext(),"录音停止了哦",Toast.LENGTH_SHORT).show();

                            stopSelf();
                        }catch (Exception err)
                        {
                            err.printStackTrace();
                        }

                    }

            }


        }
    }
}
